package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.AdministrativeRegionController
import com.zxy.supplier_system.server.repository.AdministrativeRegionRepository
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service

@Service
class AdministrativeRegionService(
    private val administrativeRegionRepository: AdministrativeRegionRepository
) {


    // 缓存名称
    companion object {
        const val REGION_TREE_CACHE = "regionTreeCache"
    }

    // 获取完整的省市区树形结构
    @Cacheable(value = [REGION_TREE_CACHE], key = "'fullRegionTree'")
    fun getFullRegionTree(): List<AdministrativeRegionController.AdministrativeRegionTreeResponse> {
        // 一次性获取所有省市区数据（只查询需要的字段）
        val regions = administrativeRegionRepository.findAllRegionProjections()

        // 构建内存中的映射关系
        val regionMap = mutableMapOf<String, AdministrativeRegionController.AdministrativeRegionTreeResponse>()
        val childrenMap = mutableMapOf<String, MutableList<AdministrativeRegionController.AdministrativeRegionTreeResponse>>()

        // 第一遍遍历：创建所有节点
        regions.forEach {
            regionMap[it.code] = AdministrativeRegionController.AdministrativeRegionTreeResponse(
                code = it.code,
                name = it.name,
                children = mutableListOf()
            )
        }

        // 第二遍遍历：构建父子关系
        regions.forEach {
            val parentCode = it.parentCode
            val current = regionMap[it.code] ?: return@forEach

            if (parentCode != null) {
                val parentChildren = childrenMap.getOrPut(parentCode) { mutableListOf() }
                parentChildren.add(current)
            }
        }

        // 第三遍遍历：设置子节点
        childrenMap.forEach { (code, children) ->
            regionMap[code]?.children = children
        }

        // 返回所有根节点（省份）
        return regions.filter { it.parentCode == null }
            .mapNotNull { regionMap[it.code] }
    }


}